<?php

namespace App\Admin\Controllers;

use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use App\Models\Requirement;
use App\Models\AdminUserRequirement;
use App\Models\AdminUserLog;
use Illuminate\Support\MessageBag;

class AdminUserLogController extends Form
{
    /**
     * The form title.
     *
     * @var  string
     */
    public $title = '日志上报';

    /**
     * Handle the form request.
     *
     * @param  Request $request
     *
     * @return  \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $data = $request->all();
        $admin_user_id = Admin::user()->id;
        $today = now()->toDateString(); // 获取今天的日期，格式为 'Y-m-d'  
  
        $admin_user_requirements = (new AdminUserRequirement())  
            ->where('admin_user_id', $admin_user_id)  
            ->where(function ($query) use ($today) {  
                $query->where('log_finished', 0)  
                      ->orWhere(function ($subQuery) use ($today) {  
                          $subQuery->where('log_finished', 1)  
                                   ->whereDate('updated_at', $today);  
                      });  
            })  
            ->whereIn('status', ['未开始', '进行中', '停滞', '已完成'])  
            ->with('requirement', 'requirement.module', 'requirement.module.project')  
            ->get();
        foreach($admin_user_requirements as $k=>$admin_user_requirement)
        {
            $already_log = (new AdminUserLog())->where([
                ['admin_user_requirement_id',$admin_user_requirement->id],
                ['date',date("Ymd",time())]
            ])->first();
            if(empty($already_log)){
                $admin_log = new AdminUserLog();
            }else{
                $admin_log = $already_log;
            }
            
            $admin_log->date = date("Ymd",time());
            $admin_log->admin_user_id = $admin_user_id;
            $admin_log->admin_user_requirement_id =$admin_user_requirement->id;
            if(isset($data['description'.$admin_user_requirement->id])){
                $admin_log->description = $data['description'.$admin_user_requirement->id];
            }
            if(isset($data['persentage'.$admin_user_requirement->id])){
                $admin_log->persentage = $data['persentage'.$admin_user_requirement->id];
            }
            if(isset($data['give_status'.$admin_user_requirement->id])){
                $admin_log->give_status =$data['give_status'.$admin_user_requirement->id];
            }
            if(isset($data['status'.$admin_user_requirement->id])){
                $admin_log->status =$data['status'.$admin_user_requirement->id];
            }
            if(isset($data['times'.$admin_user_requirement->id])){
                $admin_log->times =$data['times'.$admin_user_requirement->id];
            }
            if(isset($data['stop_reason'.$admin_user_requirement->id])){
                $admin_log->stop_reason =$data['stop_reason'.$admin_user_requirement->id];
            }
            if(isset($data['plan_date'.$admin_user_requirement->id])){
                $admin_log->plan_date =$data['plan_date'.$admin_user_requirement->id];
            }
            if(isset($data['not_start_reason'.$admin_user_requirement->id])){
                $admin_log->not_start_reason = $data['not_start_reason'.$admin_user_requirement->id];
            }
            $admin_log->save();

            //更新任务状态
            $admin_user_requirement->status=$data['status'.$admin_user_requirement->id];
            if(isset($data['persentage'.$admin_user_requirement->id])){
                $admin_user_requirement->persentage=$data['persentage'.$admin_user_requirement->id];
            }

            if($admin_user_requirement->status == '已完成'){
                $admin_user_requirement->log_finished=1;
            }
            
            $admin_user_requirement->save();
        }
        
        admin_success('日志更新成功');

        return redirect('/admin/logs');
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $admin_user_id = Admin::user()->id;
        $today = now()->toDateString(); // 获取今天的日期，格式为 'Y-m-d'  

        $admin_user_requirements = (new AdminUserRequirement())  
            ->where('admin_user_id', $admin_user_id)  
            ->where(function ($query) use ($today) {  
                $query->where('log_finished', 0)  
                      ->orWhere(function ($subQuery) use ($today) {  
                          $subQuery->where('log_finished', 1)  
                                   ->whereDate('updated_at', $today);  
                      });  
            })  
            ->whereIn('status', ['未开始', '进行中', '停滞', '已完成'])  
            ->with('requirement', 'requirement.module', 'requirement.module.project')  
            ->get();
        foreach($admin_user_requirements as $k=>$admin_user_requirement)
        {
            $this->html('<hr>');
            $this->html('<a href="/admin/admin_user_requirement/'.$admin_user_requirement->id.'" target="_blank" >'.$admin_user_requirement->requirement->module->project->name.'-'.$admin_user_requirement->requirement->module->name.'-'.$admin_user_requirement->requirement->name.'</a>','任务<b>'.($k+1).'</b>');
            
            $last_log ='';
            $last_log_stcs = (new AdminUserLog)->where('admin_user_requirement_id',$admin_user_requirement->id)->orderBy('date','DESC')->get();

            if(!$last_log_stcs->isEmpty()){
                $last_log .= <<<EOF
                    <table style="border: 1px solid black; border-collapse: collapse;">
                    <tr>
                        <th style="border: 1px solid black;padding: 5px;">日期</th>
                        <th style="border: 1px solid black;padding: 5px;">任务状态</th>
                        <th style="border: 1px solid black;padding: 5px;">计划交付日期</th>
                        <th style="border: 1px solid black;padding: 5px;">停滞原因</th>
                        <th style="border: 1px solid black;padding: 5px;">未开始原因</th>
                        <th style="border: 1px solid black;padding: 5px;">当日耗时</th>
                        <th style="border: 1px solid black;padding: 5px;">预计交付状态</th>
                        <th style="border: 1px solid black;padding: 5px;">已完成比例</th>
                        <th style="border: 1px solid black;padding: 5px;">当日工作内容描述</th>
                    </tr>
                EOF;
                foreach($last_log_stcs as $last_log_stc){
                    $last_log .= "<tr>";
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->date."</td>";//日期
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->status."</td>";//任务状态
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->plan_date."</td>";//计划交付日期
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->stop_reason."</td>";//停滞原因
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->not_start_reason."</td>";//未开始原因
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->times."</td>";//当日耗时
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->give_status."</td>";//交付状态
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->persentage."</td>";//已完成比例
                    $last_log .= "<td style='border: 1px solid black;padding: 5px;'>".$last_log_stc->description."</td>";//工作内容描述                    
                    // ，任务状态：".$last_log_stc->status.",交付状态：".$last_log_stc->give_status."，耗时：".$last_log_stc->time.($last_log_stc->status!='已完成'?("，已完成比例：".$last_log_stc->persentage."%"):"，已完成比例：100%")."，工作描述：".$last_log_stc->description;
                    
                    $last_log .= "</tr>";
                }
                $last_log .= <<<EOF
                </table>
            EOF;
                $this->html($last_log,'任务记录');
            }else{
                $this->html('空','任务记录');
            }
            $already_log = (new AdminUserLog())->where([
                ['admin_user_requirement_id',$admin_user_requirement->id],
                ['date',date("Ymd",time())]
            ])->first();

            if(empty($already_log)){
                $this->date('计划交付日期')->format('YYYY-MM-DD');
                $this->radio('status'.$admin_user_requirement->id,'任务状态')->options(['未开始' => '未开始', '进行中'=> '进行中','停滞'=>'停滞','已完成'=>'已完成'])->default($admin_user_requirement->status)
                ->when('停滞',function()use($admin_user_requirement){
                    $this->text('stop_reason'.$admin_user_requirement->id,'停滞原因');
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default(0);
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成']);
                    $this->rate('persentage'.$admin_user_requirement->id,'已完成比例')->setWidth(2, 2);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述')->help('非必填');
                })->when('未开始',function()use($admin_user_requirement){
                    $this->text('not_start_reason'.$admin_user_requirement->id,'未开始原因');
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成']);
                })->when('进行中',function()use($admin_user_requirement){
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default(0);
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成']);
                    $this->rate('persentage'.$admin_user_requirement->id,'已完成比例')->setWidth(2, 2);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述');
                })->when('已完成',function()use($admin_user_requirement){
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default(0);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述');;
                });
            }else{
       
                $this->date('plan_date'.$admin_user_requirement->id,'计划交付日期')->format('YYYY-MM-DD')->default($already_log->plan_date);
                $this->radio('status'.$admin_user_requirement->id,'任务状态')->options(['未开始' => '未开始', '进行中'=> '进行中','停滞'=>'停滞','已完成'=>'已完成'])->default($already_log->status)
                ->when('停滞',function()use($admin_user_requirement,$already_log){
                    $this->text('stop_reason'.$admin_user_requirement->id,'停滞原因')->default($already_log->stop_reason);
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default($already_log->times);
                    
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成'])
                    ->default($already_log->give_status)->value($already_log->give_status);
                    
                    $this->rate('persentage'.$admin_user_requirement->id,'已完成比例')->setWidth(2, 2)->default($already_log->persentage);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述')->help('非必填')->default($already_log->description);
                })->when('未开始',function()use($admin_user_requirement,$already_log){
                    $this->text('not_start_reason'.$admin_user_requirement->id,'未开始原因')->default($already_log->not_start_reason);
                    
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成'])
                    ->default($already_log->give_status);
                })->when('进行中',function()use($admin_user_requirement,$already_log){
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default($already_log->times);
                    
                    $this->radio('give_status'.$admin_user_requirement->id,'预计交付状态')->options(['提前完成' => '提前完成', '按时完成'=> '按时完成','时间紧迫'=>'时间紧迫','无法达成'=>'无法达成'])
                    ->default($already_log->give_status);
                    $this->rate('persentage'.$admin_user_requirement->id,'已完成比例')->setWidth(2, 2)->default($already_log->persentage);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述')->default($already_log->description);
                })->when('已完成',function()use($admin_user_requirement,$already_log){
                    $this->text('times'.$admin_user_requirement->id,'今日耗时(小时）')->setWidth(2, 2)->default($already_log->times);
                    $this->text('description'.$admin_user_requirement->id,'当日工作内容描述')->default($already_log->description);
                });
            }
            


        }
    }

    /**
     * The data of the form.
     *
     * @return  array $data
     */
    public function data()
    {

        return [
            'name'       => 'John Doe',
            'email'      => 'John.Doe@gmail.com',
            'created_at' => now(),
        ];
    }
}